package com.bright.hxj.qchz.service;

import com.bright.ghj.common.cache.RedisCache;
import com.bright.hxj.qchz.constant.SystemConstant;
import com.bright.hxj.qchz.mapper.CommonMapper;
import com.bright.hxj.qchz.pojo.bo.DuijieReturnMsg;
import com.bright.hxj.qchz.pojo.bo.Duijie_ShiJieShouData;
import com.bright.hxj.qchz.pojo.bo.RoleInfo;
import com.bright.hxj.qchz.pojo.po.Duijie_ShiJieShouDeploy;
import com.bright.hxj.qchz.pojo.po.Duijie_ShiJieShouDeploy_TablePana;
import com.bright.hxj.qchz.pojo.po.Duijie_ShiJieShouUser;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Component;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import java.sql.SQLException;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @Author hxj
 * @Date 2025/1/8 19:43
 * @Description 数据DAO操作类
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class Duijie_QCHZ_DataManager implements InitializingBean {

    private final RedisCache redisCache;
    private final CommonMapper commonMapper;

    private final Duijie_ShiJieShouCommonManager duijie_shiJieShouCommonManager;

    @Override
    public void afterPropertiesSet() throws Exception {
        // 初始化时查表赋值清查年份等
        initYears();
    }

    public RoleInfo insertOrUpdate_toDB(String userName, JSONObject jsonObject, String xmbm, Duijie_ShiJieShouDeploy deployOfMethod) {
        // 存进redis（不存了 查的时候再存）
//        Duijie_ShiJieShouDeploy deploy = getDeployByMethodName(methodName);
//        if (needToPutInRedis(deploy)) {
//            String ztId = formattedJSONObj.getString("ztid");// TODO 年报是distid
//            String key = getDataTableRedisCacheKey(ztId, methodName);
//            JSONArray jsonArray = formattedJSONObj.getJSONArray(deploy.getType().toUpperCase());
//            // 先清除数据
////            redisCache.deleteObject(key);
//            // 存进redis 30分钟内有效
//            redisCache.setCacheObject(key, jsonArray, 30, TimeUnit.MINUTES);
//        }

        // 原来的写法是调用了tdlz_ht里市对接的insertOrUpdate
//        try {
//            log.info("开始执行保存业务 {}", methodName);
//            Thread.sleep(20 * 1000);
//            log.info("保存完毕 {}", methodName);
//        } catch (InterruptedException e) {
//            throw new RuntimeException(e);
//        }
//        return null;
        return duijie_shiJieShouCommonManager.insertOrUpdate_toDB(userName, jsonObject, xmbm, deployOfMethod);
    }

    private static boolean needToPutInRedis(Duijie_ShiJieShouDeploy deploy) {
        // TODO 判断当前表是否要存进redis 只要涉及到跨表校验的都要存
        return true;
    }

    public void initYears() {
        // 改成用MyBatisPlus
//        List<List<Object>> lists = jdbcTemplate.queryForListList("select top 1 years, qcNo, qcName from qc where runflag=1 and okflag=1");
//        if (lists.size() > 0) {
//            years = (int) lists.get(0).get(0);
//            qcNo = (String) lists.get(0).get(1);
//            qcName = (String) lists.get(0).get(2);
//        } else {
//            years = -1; // 查过qc表不存在有效数据
//        }
        Map<String, Object> params = new HashMap<>(2);
        params.put("runFlag", 1);
        params.put("okFlag", 1);
        List<Map<String, Object>> qcList = commonMapper.selectData("qc", "years,qcNo,qcName", params, null);
        if (qcList.size() > 0) {
            Map<String, Object> qc = qcList.get(0);
            SystemConstant.YEARS = (Integer) qc.get("years");
            SystemConstant.QCNO = (String) qc.get("qcNo");
            SystemConstant.QCNAME = (String) qc.get("qcName");
            log.info("清查参数：{} {} {}", SystemConstant.YEARS, SystemConstant.QCNO, SystemConstant.QCNAME);
        }
    }


    public List<Map<String, String>> getDataByTableNameAndZtId(String table, String ztId, Duijie_ShiJieShouDeploy deploy) {
        if (deploy == null) {
            throw new RuntimeException("找不到" + table + "表的字段配置");
//            return result;
        }

        List<Map<String, String>> result = new ArrayList<>();
        List<Duijie_ShiJieShouDeploy_TablePana> tablePanas = deploy.getTablePanas();

        // 因为queryForMapMap返回的列名全是大写 改成根据deploy配置的tablePana获取
        List<String> columns = new ArrayList<>();
        for (Duijie_ShiJieShouDeploy_TablePana tablePana : tablePanas) {
            columns.add(tablePana.getTcolumn());
        }

        String ztIdColumn;
        List<String> mainKeys = deploy.getMainKeys();
        if (mainKeys.contains("ztid")) {
            ztIdColumn = "ztid";
        } else {
            ztIdColumn = "distid";
        }

        // 先从Redis取 Redis没有才查数据库
//        List<Map<String, Object>> lists = new ArrayList<>();
        String cacheKey = getDataTableRedisCacheKey(ztId, deploy.getType());
        Object cacheObject = redisCache.getCacheObject(cacheKey);
        if (cacheObject != null) {
            result = (List<Map<String, String>>) cacheObject;
        } else {

            // MyBatisPlus查询动态sql
//            String sql = "select " + StringUtils.join(columns.toArray(), ",") + " from " + deploy.getTableName() + " where " + ztIdColumn + "=?";
//        List<List<Object>> lists = duijie_shi_jdbcTemplate.queryForListList(sql, new Object[]{ztId});
            Map<String, Object> params = new HashMap<>(1);
            params.put(ztIdColumn, ztId);
            List<Map<String, Object>> lists = commonMapper.selectData(deploy.getTableName(), StringUtils.join(columns.toArray(), ","), params, null);


            // 调整类型
            for (Map<String, Object> list : lists) {
                int i = 0;
                Map<String, String> eachLine = new HashMap<>(); // key=字段名 value=值
                for (Object eachValue : list.values()) {
                    eachLine.put(columns.get(i), String.valueOf(eachValue));
                    i++;
                }
                result.add(eachLine);
            }

            // 存进redis 30分钟内有效
            redisCache.setCacheObject(cacheKey, result, 30, TimeUnit.MINUTES);
        }
        return result;
    }

    private String getDataTableRedisCacheKey(String ztId, String methodName) {
        return ztId + "." + methodName + "_data";
    }


    public void testMapper() {
//        commonMapper.insertData()
    }

}
